<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <div class="search-wrapper">
      <el-form ref="queryFormRef" :model="stationQueryForm" :inline="true">
        <el-form-item :label="$t('station.stationName')" prop="stationId">
          <el-select
            v-model="stationQueryForm.stationId"
            :placeholder="
              $t('common.placeholderSelect') + $t('station.stationName')
            "
            clearable
          >
            <el-option
              v-for="(item, index) in stationList"
              :key="index"
              :label="locale ? item.stationCnName : item.stationEnName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="search" type="primary" icon="Search">{{
              $t("common.search")
            }}
          </el-button>
          <el-button @click="addStation" type="primary" icon="Plus">{{
              $t("common.add")
            }}
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 2. 引入通用表单对话框组件 -->
    <CommonFormDialog
      :dialog-title="dialogTitle"
      v-model="dialogVisible"
      :dialog-width="dialogWidth"
      :form-data="stationForm"
      :form-rules="stationRules"
      :submit-loading="submitLoading"
      @close="close"
      @cancel="cancel"
      @submit="handleFormSubmit"
      @before-close="handleDialogBeforeClose"
      ref="dialogRef"
    >
      <!-- 2.1 自定义表单项（插槽：标签的"名称"和"排序"） -->
      <template #formItems>
        <el-form-item :label="$t('station.pkey')" prop="pkey">
          <el-input
              v-model="stationForm.pkey"
              :placeholder="
              $t('common.placeholderInput') + $t('station.pkey')
            "
              clearable
              maxLength="50"
          />
        </el-form-item>
        <el-form-item :label="$t('station.stationCnName')" prop="stationCnName">
          <el-input
            v-model="stationForm.stationCnName"
            :placeholder="
              $t('common.placeholderInput') + $t('station.stationCnName')
            "
            clearable
            maxLength="50"
          />
        </el-form-item>
        <el-form-item :label="$t('station.stationEnName')" prop="stationEnName">
          <el-input
            v-model="stationForm.stationEnName"
            :placeholder="
              $t('common.placeholderInput') + $t('station.stationEnName')
            "
            clearable
            maxLength="50"
          />
        </el-form-item>
        <el-form-item :label="$t('station.stationEnable')" prop="stationEnable">
          <el-select
            v-model="stationForm.stationEnable"
            :placeholder="
              $t('common.placeholderSelect') + $t('station.stationEnable')
            "
            clearable
          >
            <el-option
              v-for="(item, index) in stationEnableEnums"
              :key="index"
              :label="locale ? item.cndesc : item.endesc"
              :value="item.code"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('station.staitonStorageType')" prop="staitonStorageType">
          <el-select
              v-model="stationForm.staitonStorageType"
              :placeholder="
              $t('common.placeholderSelect') + $t('station.staitonStorageType')
            "
              clearable
          >
            <el-option
                v-for="(item, index) in staitonStorageTypeEnums"
                :key="index"
                :label="locale ? item.cndesc : item.endesc"
                :value="item.code"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('station.stationStatus')" prop="stationStatus">
          <el-select
            v-model="stationForm.stationStatus"
            :placeholder="
              $t('common.placeholderSelect') + $t('station.stationStatus')
            "
            clearable
          >
            <el-option
              v-for="(item, index) in stationStaEnums"
              :key="index"
              :label="locale ? item.cndesc : item.endesc"
              :value="item.code"
            />
          </el-select>
        </el-form-item>
        <!-- 可扩展：如需其他表单项（如"颜色""描述"），直接在这里添加 -->
      </template>
    </CommonFormDialog>

    <el-card>
      <el-row>

        <el-col :span="24">
          <el-card
            >
            <!-- 场站管理标题 -->
            <div class="station-management-header">
              <div class="title-wrapper">
                <el-icon class="title-icon"><OfficeBuilding /></el-icon>
                <h3 class="station-title">{{$t('station.stationManagement')}}</h3>
              </div>
              <div class="station-stats">
                <span class="stat-item">
                  <span class="stat-label">{{$t('station.stationnNum')}}：</span>
                  <span class="stat-value">{{ total }}</span>
                </span>
                <span class="stat-item">
                  <span class="stat-label">{{$t('station.statonEnableNum')}}：</span>
                  <span class="stat-value">{{ enabledStations }}</span>
                </span>
              </div>
            </div>
            <!-- 数据表格 -->
            <el-table
              max-height="600"
              :data="tableData"
              style="width: 100%"
              @selection-change="handleSelectionChange"
            >
              <el-table-column
                :label="$t('common.sn')"
                type="index"
                width="150"
              />
              <el-table-column
                  :label="$t('station.pkey')"
                  align="center"
                  prop="pkey"
              />
              <el-table-column
                :label="$t('station.stationCnName')"
                align="center"
                prop="stationCnName"
              />
              <el-table-column
                :label="$t('station.stationEnName')"
                align="center"
                prop="stationEnName"
              />
              <el-table-column
                  :label="$t('station.staitonStorageType')"
                  align="center"
                  prop="staitonStorageType"
              > <template #default="scope">
                {{
                  getstaitonStorageTypeById(scope.row.staitonStorageType)
                }}
              </template>
              </el-table-column>
              <el-table-column
                :label="$t('common.createTime')"
                align="center"
                prop="createTime"
              />
              <el-table-column
                :label="$t('common.updateTime')"
                align="center"
                prop="updateTime"
              />
              <el-table-column
                label="操作"
                align="center"
                width="200"
                fixed="right"
              >
                <template #default="scope">
                  <el-button
                    type="primary"
                    link
                    icon="Edit"
                    @click="updateStation(scope.row)"
                    >{{ $t("common.edit") }}</el-button
                  >
                  <el-button
                    type="danger"
                    link
                    icon="Delete"
                    @click="deleteStation(scope.row)"
                    >{{ $t("common.delete") }}</el-button
                  >
                  <el-button
                      type="default"
                      link
                      @click="goGateway(scope.row)"
                  >{{ $t("common.gateway") }}</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
            <!-- 分页组件 -->
            <div class="pagination-container">
              <el-pagination
                v-model:current-page="stationQueryForm.pageNum"
                v-model:page-size="stationQueryForm.pageSize"
                :page-sizes="[10, 20, 30, 50]"
                :total="total"
                :background="true"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </div>
          </el-card>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script setup>
import {
  getstationListApi,
  getstationPageApi,
  addStationApi,
  updateStationApi,
  delStationApi,
} from "@/api/ems/station/station.ts";
import { getEnumListByType } from "@/api/enums";
import { ElMessage, ElMessageBox, ElLoading } from "element-plus";
import { useI18n } from "vue-i18n";
import {staitonEnum} from "@/enum/staitonEnum"
import CommonFormDialog from "@/components/Modal/basicModal.vue"; // 引入通用组件
import { reactive, ref, onMounted, onUnmounted, watch, nextTick, computed } from "vue";
import { OfficeBuilding } from "@element-plus/icons-vue";
import { useRoute, useRouter } from "vue-router";
import {EmsCommonEnums} from "@/enum/common/EmsCommonEnums.ts";
const tableData = ref(); //表格数组
const locale = ref(window.localStorage.getItem("locale") == "zh-CN");
const total = ref(0);
const dialogWidth = ref("600px");
// 1. 对话框状态
const dialogVisible = ref(false); // 对话框是否显示
const router = useRouter();
const submitLoading = ref(false); // 提交按钮加载状态
const dialogRef = ref(); // 通用对话框组件引用
const { t } = useI18n();
const dialogTitle = ref(); // 对话框标题
// 2. 场站查询表单数据
const stationQueryForm = reactive({
  pageNum: 1,
  pageSize: 10,
  stationId: "", // 场站Id
});
// 2. 场站新增表单数据
const stationForm = reactive({
  stationCnName: "", // 场站中文名称
  stationEnName: "", // 场站英文名称
  comment: "", //场站Ip
  pkey       : "",//pkey
  isEnable: null, //场站是否可用
  stationStatus: null, //场站状态
  staitonStorageType : null //场站储能类型
});
// 3. 标签表单校验规则
const stationRules = reactive({
  pkey: [
    { required: true, message: t("common.placeholderInput"), trigger: "blur" },
    { max: 50, message: t("station.pkey"), trigger: "blur" },
  ],
  stationCnName: [
    { required: true, message: t("common.placeholderInput"), trigger: "blur" },
    { max: 50, message: t("station.inputRule"), trigger: "blur" },
  ],
  stationEnName: [
    { required: true, message: t("common.placeholderInput"), trigger: "blur" },
    { max: 50, message: t("station.inputRule"), trigger: "blur" },
  ],
});
//场站列表
const stationList = ref([]);
//场站可用列表枚举
const stationEnableEnums = ref([]);
//场站可用列表状态枚举
const stationStaEnums = ref([]);
// 计算启用场站数量
const enabledStations = computed(() => {
  if (!tableData.value) return 0;
  return tableData.value.filter(item => item.isEnable === 1).length;
});
const getstaitonStorageTypeById = (id) => {
  let res = "";
  staitonStorageTypeEnums.value?.forEach(item => {
    if (item.code == id) {
      res = locale ? item.cndesc : item.endesc;
    }
  })
  return res;
};
//查询
const search = () => {
  getSelectPage();
};
const handleSizeChange = (val) => {
  stationQueryForm.pageSize = val;
  getSelectPage();
};
const handleCurrentChange = (val) => {

  stationQueryForm.pageNum = val;
  getSelectPage();
};
const getSelectPage = () => {
  getstationPageApi(stationQueryForm).then((res) => {
    tableData.value = res.data.records;
    total.value = res.data.total;
  });
};
const getStationList = () => {
  getstationListApi().then((res) => {
    stationList.value = res.data;
  });
};
const staitonStorageTypeEnums = ref([]);//储能类型枚举
//获取场站枚举列表
const getEnumListByTypeList = async (stype) => {
  let res = await getEnumListByType({ type: stype });
  if (stype == EmsCommonEnums.CommonEnable) {
    stationEnableEnums.value = res.data;
  }
  if (stype == "stationStatus") {
    stationStaEnums.value = res.data;
  }
  if (stype == staitonEnum.StaitonStorageTypeEnum) {
    staitonStorageTypeEnums.value = res.data;
  }
};
// 关闭对话框时，触发 update:modelValue 事件
const close = () => {
  dialogVisible.value = false; // 通知父组件将 dialogVisible 设为 false
};
// 关闭对话框时，触发 update:modelValue 事件
const cancel = () => {
  dialogVisible.value = false; // 通知父组件将 dialogVisible 设为 false
};
//新增调出弹框
const addStation = () => {
  dialogVisible.value = true;
  Object.assign(stationForm, {
    id:null,
    stationCnName: "", // 场站中文名称
    stationEnName: "", // 场站英文名称
    comment: "", //场站Ip
    pkey       : "",//pkey
    isEnable: null, //场站是否可用
    stationStatus: null, //场站状态
    staitonStorageType : null //场站储能类型
  });
  dialogTitle.value = t("station.stationAdd");
};
//修改调出弹框
const stationId = ref();
const updateStation = (row) => {
  dialogTitle.value = t("station.stationUpdate");
  dialogVisible.value = true;
  stationId.value = row.id;
  Object.assign(stationForm, row);
};
const handleDialogBeforeClose = () => {
  dialogVisible.value = false; // 通知父组件将 dialogVisible 设为 false
};
//提交数据
const handleFormSubmit = () => {
  if (dialogTitle.value == t("station.stationAdd")) {
    addStationApi(stationForm).then((res) => {
      if (res.code == 200) {
        ElMessage.success(t("common.success"));
        getSelectPage();
        dialogVisible.value = false;
      } else {
        ElMessage.success(t("common.error"));
      }
    });
  } else {
    updateStationApi(Object.assign(stationForm)).then((res) => {
      if (res.code == 200) {
        ElMessage.success(t("common.success"));
        getSelectPage();
        dialogVisible.value = false;
      } else {
        ElMessage.success(t("common.error"));
      }
    });
  }
};
//跳转网关页面
const goGateway = (row) => {
  router.push({ path: "/stationMangement/gateway", query: { stationId: row.id } })
}
//删除数据
const deleteStation = (row) => {
  ElMessageBox.confirm(
    `是否确认删除`,
    "警告",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  ).then(() => {
    delStationApi(row.id).then((res) => {
      if (res.code == 200) {
        ElMessage.success(t("common.success"));
        getSelectPage();
      } else {
        ElMessage.success(t("common.error"));
      }
    });
  });
};

onMounted(() => {
  getSelectPage();
  getStationList();EmsCommonEnums
  getEnumListByTypeList(EmsCommonEnums.CommonEnable); //获取场站可用
   //获取场站可用
  getEnumListByTypeList("stationStatus"); //获取场站可用
  getEnumListByTypeList(staitonEnum.StaitonStorageTypeEnum);
});
onUnmounted(() => {});
</script>
<style lang="scss" scoped>
.app-container {
  /* 场站管理标题样式 */
  .station-management-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding: 16px 20px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-radius: 8px;
    color: white;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);

    .title-wrapper {
      display: flex;
      align-items: center;
      gap: 12px;

      .title-icon {
        font-size: 24px;
        color: #ffffff;
      }

      .station-title {
        margin: 0;
        font-size: 20px;
        font-weight: 600;
        color: #ffffff;
        text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
      }
    }

    .station-stats {
      display: flex;
      gap: 24px;

      .stat-item {
        display: flex;
        align-items: center;
        gap: 6px;
        padding: 8px 12px;
        background: rgba(255, 255, 255, 0.15);
        border-radius: 20px;
        backdrop-filter: blur(10px);

        .stat-label {
          font-size: 14px;
          opacity: 0.9;
        }

        .stat-value {
          font-size: 16px;
          font-weight: 600;
          color: #ffffff;
        }
      }
    }
  }

  /* 响应式设计 */
  @media (max-width: 768px) {
    .station-management-header {
      flex-direction: column;
      gap: 16px;
      text-align: center;

      .station-stats {
        justify-content: center;
      }
    }
  }

  .pagination-container {
    display: flex;
    justify-content: center;
    margin-top: 20px;
  }

  :deep(.el-dialog) {
    .el-dialog__body {
      padding: 20px 40px;
    }

    .el-form {
      .el-form-item {
        margin-bottom: 22px;

        &:last-child {
          margin-bottom: 0;
        }

        .el-form-item__label {
          font-weight: 500;
          padding-right: 20px;
        }
      }

      .el-select {
        width: 100%;
      }
    }
  }
}

:root[data-theme="dark"] {
  .app-container {
    :deep(.el-dialog) {
      .el-form {
        .el-input__wrapper {
          box-shadow: 0 0 0 1px var(--el-border-color) inset;
        }
      }
    }
  }
}
</style>